<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select 
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px;"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['serve:nurse:add']"
        >新增护理计划</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="nurseList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" width="150"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="护理计划名称" align="center" prop="planName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['serve:nurse:edit']"
            :disabled="scope.row.isUsedByLevel"
          >修改</el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['serve:nurse:remove']"
            :disabled="scope.row.isUsedByLevel"
          >删除</el-button>
          <el-button 
            link 
            :type="scope.row.status === 1 ? 'danger' : 'success'" 
            @click="handleToggleStatus(scope.row)" 
            v-hasPermi="['serve:nurse:edit']"
            :disabled="scope.row.isUsedByLevel"
          >{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看弹窗 -->
    <el-dialog title="查看护理计划" v-model="viewDialogVisible" width="700px" append-to-body>
      <!-- 护理计划名称（只读） -->
      <div style="margin-bottom: 20px;">
        <span style="font-weight: bold;">护理计划名称：</span>
        <span>{{ viewForm.planName }}</span>
      </div>

      <!-- 护理项目表格（只读） -->
      <div style="margin-bottom: 10px;">
        <span style="font-weight: bold;">护理项目：</span>
      </div>
      <el-table
        :data="viewForm.nursingItems"
        border
        style="width: 100%"
      >
        <el-table-column label="护理项目名称" align="center">
          <template #default="scope">
            <span>{{ getNursingItemName(scope.row.nursingItemId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="期望服务时间" align="center" prop="serviceTime" />
        <el-table-column label="执行周期" align="center">
          <template #default="scope">
            <span>{{ getCycleName(scope.row.executionCycle) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行频次(次)" align="center" prop="executionFrequency" />
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/修改弹窗 -->
    <el-dialog :title="title" v-model="dialogVisible" width="1200px" append-to-body>
      <el-form ref="nurseRef" :model="form" :rules="rules" label-width="80px">
        <!-- 计划名称 -->
        <el-form-item label="计划名称" prop="planName">
          <el-input 
            v-model="form.planName"
            placeholder="请输入" 
            maxlength="20"
            show-word-limit
            style="width: 400px;"
          />
        </el-form-item>

        <!-- 护理项目动态表格 -->
        <el-form-item label="护理项目" prop="nursingItems">
          <el-table
            :data="form.nursingItems"
            border
            :row-key="(row, index) => index"
            style="width: 100%"
          >
            <!-- 护理项目下拉 -->
            <el-table-column label="护理项目名称" width="260">
              <template #default="scope">
                <el-select
                  v-model="scope.row.nursingItemId"
                  placeholder="请选择"
                  clearable
                  required
                  style="width: 240px;"
                >
                  <el-option
                    v-for="item in nursingItemOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 服务时间 -->
            <el-table-column label="期望服务时间" width="220">
              <template #default="scope">
                <el-time-picker
                  v-model="scope.row.serviceTime"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="选择时间"
                  :default-value="new Date(2000, 1, 1, 8, 0)"
                  required
                  style="width: 200px;"
                />
              </template>
            </el-table-column>

            <!-- 执行周期 -->
            <el-table-column label="执行周期" width="200">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.executionCycle" 
                  placeholder="请选择"
                  required
                  style="width: 180px;"
                >
                  <el-option label="每日" :value="1" />
                  <el-option label="每周" :value="2" />
                  <el-option label="每月" :value="3" />
                </el-select>
              </template>
            </el-table-column>

            <!-- 执行频次 -->
            <el-table-column label="执行频次(次)" width="200">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.executionFrequency"
                  :min="1"
                  :max="7"
                  placeholder="请输入"
                  :default-value="1"
                  required
                  style="width: 180px;"
                />
              </template>
            </el-table-column>

            <!-- 行操作 -->
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <div style="display: flex; gap: 5px;">
                  <!-- 删除行：只剩1行时禁用 -->
                  <el-button
                    icon="Minus"
                    type="danger"
                    plain
                    size="small"
                    @click="handleDeleteRow(scope.$index)"
                    :disabled="form.nursingItems.length === 1"
                  />
                  <!-- 新增行：仅第一行显示 -->
                  <el-button
                    v-if="scope.$index === 0"
                    icon="Plus"
                    type="success"
                    plain
                    size="small"
                    @click="handleAddRow"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Nurse">
// 导入接口
import { listNurse, getNurse, delNurse, updateNurse ,updateWithItems} from "@/api/serve/nurse";
import { addWithItems } from "@/api/serve/nurse"; // 新增带护理项目的接口
import { listEnableNursingItems } from "@/api/serve/project"; // 启用的护理项目下拉接口

// 导入Vue工具
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from "vue";

// 若依框架工具（proxy）
const { proxy } = getCurrentInstance();

// 1. 基础状态变量
const nurseList = ref([]); // 护理计划列表数据
const dialogVisible = ref(false); // 弹窗显隐（统一用这个，删除原来的open）
const viewDialogVisible = ref(false); // 查看弹窗显隐
const loading = ref(true); // 加载状态
const showSearch = ref(true); // 搜索栏显隐
const ids = ref([]); // 选中的ID集合
const single = ref(true); // 是否单选
const multiple = ref(true); // 是否多选
const total = ref(0); // 总条数
const title = ref(""); // 弹窗标题

// 2. 下拉选项：启用的护理项目
const nursingItemOptions = ref([]);

// 查看表单数据
const viewForm = ref({
  planName: '',
  nursingItems: []
});

// 3. 表单数据与校验规则
const data = reactive({
  // 表单数据
  form: {
    id: null,
    planName: null,
    creator: null,
    createTime: null,
    status: 1, // 默认启用
    isDeleted: 0,
    extraField1: null,
    extraField2: null,
    // 护理项目列表（默认1行初始数据）
    nursingItems: [
      {
        nursingItemId: null,
        serviceTime: "08:00",
        executionCycle: 2, // 默认每周
        executionFrequency: 1, // 默认1次
      },
    ],
  },
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: null,
    status: null,
  },
  // 表单校验规则
  rules: {
    // 计划名称校验
    planName: [
      { required: true, message: "计划名称不能为空", trigger: "blur" },
      { max: 20, message: "计划名称最多20个字符", trigger: "blur" },
    ],
    // 护理项目校验（至少1项，且每项都选了项目）
    nursingItems: [
      {
        required: true,
        validator: (rule, value, callback) => {
          // 校验是否有数据
          if (!value || value.length === 0) {
            return callback(new Error("请至少添加一项护理项目"));
          }
          // 校验每一行是否选了护理项目
          const hasEmpty = value.some((item) => !item.nursingItemId);
          if (hasEmpty) {
            return callback(new Error("所有护理项目均需选择具体项目"));
          }
          callback(); // 校验通过
        },
        trigger: "change",
      },
    ],
  },
});

// 解构响应式数据
const { queryParams, form, rules } = toRefs(data);

// 4. 核心方法
/**
 * 1. 获取启用的护理项目（下拉选项）
 */
const getEnableNursingItemsData = () => {
  listEnableNursingItems().then((res) => {
    nursingItemOptions.value = res.data || [];
  });
};

/**
 * 2. 查询护理计划列表
 */
function getList() {
  loading.value = true;
  listNurse(queryParams.value).then((response) => {
    nurseList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  });
}

/**
 * 3. 表单重置
 */
function reset() {
  form.value = {
    id: null,
    planName: null,
    creator: null,
    createTime: null,
    status: 1,
    isDeleted: 0,
    extraField1: null,
    extraField2: null,
    // 重置时保留1行初始护理项目
    nursingItems: [
      {
        nursingItemId: null,
        serviceTime: "08:00",
        executionCycle: 2,
        executionFrequency: 1,
      },
    ],
  };
  // 重置表单校验状态
  if (proxy.$refs.nurseRef) {
    proxy.resetForm("nurseRef");
  }
}

/**
 * 4. 搜索按钮
 */
function handleQuery() {
  queryParams.value.pageNum = 1; // 重置页码
  getList();
}

/**
 * 5. 重置搜索
 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/**
 * 6. 表格多选事件
 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1; // 不是1条则禁用单选操作
  multiple.value = selection.length === 0; // 0条则禁用多选操作
}

/**
 * 7. 新增按钮
 */
function handleAdd() {
  reset(); // 重置表单
  getEnableNursingItemsData(); // 加载下拉选项
  dialogVisible.value = true;
  title.value = "新增护理计划";
}

/**
 * 8. 修改按钮
 */
function handleUpdate(row) {
  reset(); // 重置表单
  getEnableNursingItemsData(); // 加载下拉选项
  
  // 获取选中的ID（表格多选/行内修改）
  const _id = row?.id || ids.value[0];
  getNurse(_id).then((response) => {
    form.value = { ...response.data };
    // 若后端返回了nursingItems，直接赋值；否则保留初始1行
    if (!form.value.nursingItems || form.value.nursingItems.length === 0) {
      form.value.nursingItems = [
        {
          nursingItemId: null,
          serviceTime: "08:00",
          executionCycle: 2,
          executionFrequency: 1,
        },
      ];
    }
    dialogVisible.value = true;
    title.value = "修改护理计划";
  });
}

/**
 * 9. 动态表格：新增一行
 */
function handleAddRow() {
  form.value.nursingItems.push({
    nursingItemId: null,
    serviceTime: "08:00",
    executionCycle: 2,
    executionFrequency: 1,
  });
}

/**
 * 10. 动态表格：删除一行
 */
function handleDeleteRow(index) {
  form.value.nursingItems.splice(index, 1);
}

/**
 * 11. 提交表单
 */
function submitForm() {
  proxy.$refs.nurseRef.validate((valid) => {
    if (valid) {
      // 修改场景：调用原update接口
      if (form.value.id) {
        updateWithItems(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          dialogVisible.value = false;
          getList();
        });
      } 
      // 新增场景：调用带护理项目的addWithItems接口
      else {
        addWithItems(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          dialogVisible.value = false;
          getList();
        });
      }
    }
  });
}

/**
 * 12. 取消按钮
 */
function cancel() {
  dialogVisible.value = false;
  reset();
}

/**
 * 13. 删除按钮
 */
function handleDelete(row) {
  const _ids = row?.id || ids.value;
  proxy.$modal.confirm(`是否确认删除护理计划编号为"${_ids}"的数据？`).then(() => {
    return delNurse(_ids);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    getList();
  }).catch(() => {});
}

/**
 * 14. 导出按钮
 */
function handleExport() {
  proxy.download("serve/nurse/export", { ...queryParams.value }, `护理计划_${new Date().getTime()}.xlsx`);
}

/**
 * 15. 切换启用/禁用状态
 */
function handleToggleStatus(row) {
  const targetStatus = row.status === 1 ? 0 : 1;
  updateNurse({ id: row.id, status: targetStatus }).then(() => {
    proxy.$modal.msgSuccess(targetStatus === 1 ? "启用成功" : "禁用成功");
    getList();
  }).catch(() => {
    proxy.$modal.msgError(targetStatus === 1 ? "启用失败" : "禁用失败");
  });
}

/**
 * 16. 查看护理计划
 */
function handleView(row) {
  // 加载护理项目下拉选项（用于显示护理项目名称）
  getEnableNursingItemsData();
  
  // 获取护理计划详情
  getNurse(row.id).then((response) => {
    viewForm.value = {
      planName: response.data.planName || '',
      nursingItems: response.data.nursingItems || []
    };
    viewDialogVisible.value = true;
  });
}

/**
 * 17. 获取护理项目名称（根据ID）
 */
function getNursingItemName(itemId) {
  const item = nursingItemOptions.value.find(opt => opt.id === itemId);
  return item ? item.name : '-';
}

/**
 * 18. 获取执行周期名称
 */
function getCycleName(cycle) {
  const cycleMap = {
    1: '每日',
    2: '每周',
    3: '每月'
  };
  return cycleMap[cycle] || '-';
}

// 5. 页面加载时执行
onMounted(() => {
  getList(); // 加载护理计划列表
});
</script>